package com.metacube.questionbank.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.metacube.questionbank.dao.VoteDAO;
import com.metacube.questionbank.model.Answer;
import com.metacube.questionbank.service.VoteService;

/*
 * @author Team Neeraj Jain
 * */
@Service
public class VoteServiceImpl implements VoteService {
	@Autowired
	VoteDAO votedao;
	@Autowired
	UserServiceImpl userService;
	@Autowired
	AnswerServiceImpl answerService;

	/*
	 * @param answerId id of answer This method returns no of likes for a
	 * particular answer
	 * 
	 * @return nLikes no. of likes
	 */
	public int getUpvotesForAnswer(int answerId) {
		int nLikes = votedao.getUpvotesForAnswer(answerId);
		return nLikes;
	}

	/*
	 * @param answerId id of answer This method returns no of dislikes for a
	 * particular answer
	 * 
	 * @return nLikes no. of dislikes
	 */
	public int getDownvotesForAnswer(int answerId) {
		int nDislikes = votedao.getdownvotesForAnswer(answerId);
		return nDislikes;
	}

	/*
	 * @param answers list of answers This method returns a list that contains
	 * no. of likes for each answer in the list.
	 * 
	 * @return list of likes
	 */
	public List<Integer> getUpVotes(List<Answer> answers) {
		List<Integer> upVotes = new ArrayList<Integer>();
		for (int ansCounter = 0; ansCounter < answers.size(); ansCounter++) {
			upVotes.add(getUpvotesForAnswer(answers.get(ansCounter).getAnsId()));
		}
		return upVotes;
	}

	/*
	 * @param answers list of answers This method returns a list that contains
	 * no. of dislikes for each answer in the list.
	 * 
	 * @return list of dislikes
	 */
	public List<Integer> getDownVotes(List<Answer> answers) {
		List<Integer> downVotes = new ArrayList<Integer>();
		for (int ansCounter = 0; ansCounter < answers.size(); ansCounter++) {
			downVotes.add(getDownvotesForAnswer(answers.get(ansCounter)
					.getAnsId()));
		}
		return downVotes;
	}

	/*
	 * @param userId id of user who liked the answer
	 * 
	 * @param ansId id of answer
	 * 
	 * @param status like or dislike This method updates the likes or dislikes
	 * for a particular answer
	 */
	public void insertUpvoteStatus(int userId, int ansId, int status) {
		int userAId;
		if (votedao.isRecordPresent(userId, ansId) == 0) {
			votedao.insertStatus(userId, ansId, status);
		} else {
			int upVoteStatus = votedao.getUpvoteStatus(userId, ansId);
			if (upVoteStatus != status) {
				votedao.updateStatus(userId, ansId, status);
			}
		}
		userAId=answerService.getUserIdByAId(ansId);
		System.out.println("answerer id is"+userAId);
		userService.setUserRating(userAId);
	}
}